<?php

namespace App\Http\Controllers\Pay;

use App\Http\Controllers\Controller;
use DB;
use Config;

class AliPayController extends Controller
{
    public function __construct()
    {
        header("Content-type:text/html;charset=utf-8");
        //支付宝支付2.0
        require_once(app_path().'/Library/Alipay/AopSdk.php');
    }

    /**
     * 支付宝支付成功后 后续操作代码
     * 此处为接收支付宝服务器异步通知后变更订单状态
     * @param $type 处理类型：synchronous：同步通知，判断订单状态是否改变  asynchronous：异步通知，改变订单状态
     */
    protected function alipayend($info,$type)
    {
        if($type == 'synchronous'){
            //此处为同步通知，查询订单状态是否改变
            $re = 1;
        }elseif($type == 'asynchronous'){
            //此处为异步通知，变更订单状态业务逻辑
            $data = [
                'content'=>json_encode($info),
                'addtime'=>time(),
            ];
            $re = DB::table('testorder')->insert($data);
        }
        $result = $re ? true : false;
        return $result;
    }

    /**
     * 支付宝配置信息
     */
    protected function getAliInfo()
    {
        $domain_url = Config::get('zgssystem.domain_url');
        $alipay_config = array(
            'app_id'		=> Config::get('zgssystem.ali_pay_appid'),
            'merchant_private_key'	=> Config::get('zgssystem.ali_pay_merchant_private_key'),
            'alipay_public_key'		=> Config::get('zgssystem.ali_pay_public_key'),
            'sign_type'		=> strtoupper('RSA2'),
            'charset'	    => strtoupper('utf-8'),
            'format'	    => strtolower('json'),
            'gateway_url'    => "https://openapi.alipay.com/gateway.do",
            'notify_url'	=> $domain_url.'/alipay/notify',
            'return_url'	=> $domain_url.'/alipay/return',
        );
        return $alipay_config;
    }
    /**
     * alipay.trade.wap.pay
     * @param $payinfo 业务参数，支付参数。
     * @return $response 支付宝返回的信息
     */
    public function aliWapPay($payinfo)
    {
        $alipay_config = $this->getAliInfo();
        $biz_content=$this->getBizContent($payinfo);
        $request = new \AlipayTradeWapPayRequest();
        $request->setNotifyUrl($alipay_config['notify_url']);
        $request->setReturnUrl($alipay_config['return_url']);
        $request->setBizContent($biz_content);

        // 首先调用支付api
        $response = $this->aopclientRequestExecute ($request,true,$alipay_config);
        return $response;
    }

    /**
     * 获取业务请求参数的集合 bizcontent
     */
    private function getBizContent($info)
    {
        $bizcontentarr = [
            'body' => $info['body'],
            'subject' => $info['subject'],
            'out_trade_no' => $info['out_trade_no'],
            'total_amount' => $info['total_amount'],
            'product_code' => isset($info['total_amount']) ? $info['total_amount'] : 'QUICK_WAP_PAY',
            'timeout_express' => isset($info['timeout_express']) ? $info['timeout_express'] : '30m',
        ];
        $bizcontent = json_encode($bizcontentarr,JSON_UNESCAPED_UNICODE);
        return $bizcontent;
    }

    /**
     * 发起支付宝api请求
     */
    protected function aopclientRequestExecute($request,$ispage=false,$alipay_config)
    {
        $aop = new \AopClient();
        $aop->gatewayUrl = $alipay_config['gateway_url'];
        $aop->appId = $alipay_config['app_id'];
        $aop->rsaPrivateKey =  $alipay_config['merchant_private_key'];
        $aop->alipayrsaPublicKey = $alipay_config['alipay_public_key'];
        $aop->apiVersion ="1.0";
        $aop->postCharset = $alipay_config['charset'];
        $aop->format= $alipay_config['format'];
        $aop->signType=$alipay_config['sign_type'];
        // 开启页面信息输出
        $aop->debugInfo=true;
        if($ispage){
            $result = $aop->pageExecute($request,"post");
            echo $result;
        }else{
            $result = $aop->Execute($request);
        }
        return $result;
    }

    /**
     * 服务器异步通知页面路径
     */
    protected function notifyUrl(){
        $alipay_config = $this->getAliInfo();
        $return_data = $_POST;
        $result= $this->check($return_data,$alipay_config);
        if($result) {
            $trade_status = $return_data['trade_status'];
            if($trade_status == 'TRADE_FINISHED') {
                //交易完成
            }else if ($trade_status == 'TRADE_SUCCESS') {
                $this->alipayend($return_data,'asynchronous');
            }
            echo "success";		//请不要修改或删除
        }else {
            //验证失败
            echo "fail";	//请不要修改或删除
        }
    }

    /**
     * 服务器同步通知页面路径
     */
    protected function returnUrl(){
        $alipay_config = $this->getAliInfo();
        $return_data = $_GET;
        $result= $this->check($return_data,$alipay_config);
        if($result) {
            $out_trade_no = htmlspecialchars($return_data['out_trade_no']);
            $trade_no = htmlspecialchars($return_data['trade_no']);

            $re = $this->alipayend($return_data,'synchronous');
            if($re){
                return redirect('/paysuccess');
            }else{
                echo '支付异常，请联系网站客服或管理员。（需提供当前订单号【'.$out_trade_no.'】和支付宝交易号【'.$trade_no.'】）';
            }
        }else {
            //验证失败
            echo "验证失败,非支付宝返回请求";
        }
    }

    /**
     * 验签方法
     * @param $arr 验签支付宝返回的信息，使用支付宝公钥。
     * @return boolean
     */
    protected function check($arr,$config){
        $aop = new \AopClient();
        $aop->alipayrsaPublicKey = $config['alipay_public_key'];
        $result = $aop->rsaCheckV1($arr, $config['alipay_public_key'], $config['sign_type']);
        return $result;
    }

}